#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月19日

@author: Administrator
'''
from article.models import Article
from comment import settings
from comment.models import Comment
from comment.utils import get_comment_childrens
from common.core.contenttypes import fetch_content_type_id
from common.decorators import login_required
from common.templatetags.jinja2 import time_beauty
from common.utils import es
from django.http.response import HttpResponse
from django.template.response import TemplateResponse
from elasticsearch_dsl.query import Q
from elasticsearch_dsl.search import Search
from funcresource.decorators import user_funcresource
import copy
import ujson as json

@login_required
@user_funcresource
def index(request, template="comment/admin/comment/comment.html"):
    """
        func:
                               评论列表页面
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    return TemplateResponse(request, template, rsp_data)
    
@login_required
def list(request):
    """
        func:
                               用户列表
        parameters:
            start:开始下标
            length:每页展示个数
            search[value]:搜索关键字
            columns[6][search][value]:用户状态
            draw:渲染次数
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = []
    start = int(request.POST['start'])
    length = int(request.POST['length'])
    keyword = request.POST["search[value]"]
    state = request.POST.get("columns[6][search][value]", "")
    state = '' if state == '' else state[1:-1]
    draw = request.POST['draw']
    #es连接
    response = Search(using=es.es_client, index=settings.ES_INDEX_COMMENT_LIST, doc_type=settings.ES_INDEX_COMMENT_LIST_TYPE) 
    if  keyword:
        response = response.query(Q("match_phrase", text_content=keyword)) 
    if  state:
        response = response.query(Q("term", state=state)) 
    response = response.extra(from_=start, size=length) 
    response = response.sort("-id")
    result = response.execute()
    for hit in result.hits:
        record = {
            "id":hit.id,
            "user_name":hit.user_name,
            "object_id":hit.object_id,
            "parent_id":hit.parent_id,
            "floor":hit.floor,
            "text_content":hit.text_content,
            "source":settings.SOURCE_CHOICES[hit.source][1],
            "source_id":hit.source_id,
            "state_desc":settings.get_state_desc(hit.state),
        }
        rsp_data["data"].append(record)
    rsp_data["recordsTotal"] = result.hits.total
    rsp_data["recordsFiltered"] = result.hits.total
    rsp_data["draw"] = draw
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def get_comments_by_obj(request):
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    rsp_data["data"]["comments"] = []
    obj_id = request.POST["obj_id"]
    app_label = request.POST["app_label"]
    model = request.POST["model"]
    content_type = fetch_content_type_id(app_label, model)
    comments = Comment.objects.filter(object_id=obj_id, content_type=content_type, parent=None).order_by("source_id")
    for comment in comments:
        record = {
            "content":comment.content,
            "first_name":comment.user.first_name,
            "avatar_url":comment.user.profile.avatar_url,
            "create_time":time_beauty(comment.create_time),
            "childrens":get_comment_childrens(comment),
        }
        rsp_data["data"]["comments"].append(record)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
